package com.ofsoft.cms.core.uitle;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;

import java.util.List;

public class HtmlCompressCleanUtil {
    /**
     * 按目标清除某些标签
     *
     * @param str
     *            the root element to format
     * @return formatted text
     */
    public static String getPlainText(String str) {
        Document element = Jsoup.parse(str);

        FormattingVisitor formatter = new FormattingVisitor();
        NodeTraversor traversor = new NodeTraversor(formatter);
        traversor.traverse(element); // walk the DOM, and call .head() and
        element.select("span,a,u,b,font,br,pre,style,link").unwrap();
        String text = element.select("body").html();
        //text = text.replaceAll("[ ]*", "");
        text = text.replaceAll("\\n\\s*", "");
        //text = text.replaceAll("&nbsp;", "");
        //text = text.replaceAll("<[a-zA-Z0-9/]+:[\\w\\s='\"-\\:;@\\,~]+>", "");
        text = text.replaceAll("<!---->","");

        return text;
    }

    /**
     * 清除所有属性
     */
    private static class FormattingVisitor implements NodeVisitor {

        // hit when the node is first seen
        public void head(Node node, int depth) {

        }

        // hit when all of the node's children (if any) have been visited
        public void tail(Node node, int depth) {
            if (node instanceof TextNode || "img".equals(node.nodeName())|| "script".equals(node.nodeName())) {

            } else {
                List<Attribute> attrs = node.attributes().asList();

                for (int k = attrs.size()-1;k>=0; k--) {
                    String attributeKey = attrs.get(k).getKey();
                    node.removeAttr(attributeKey);
                }
                //System.out.println("------------"+node.toString());
            }


        }

    }

    /**
     * 得到纯文本
     * @param content
     * @return
     */
    public static String getText(String content){
        return content==null?"":Jsoup.parse(content).text();
    }

}
